/***************************************************************************************
* File name    :	ALGDes_PR.c
* Function     :	
* Author       : 
* Date         :
* Version      : 
* Description  :    
* ModifyRecord :
*****************************************************************************************/
#include <Utils/Type.h>
#include "ALGDes_PR.h"
#include <mbedtls/des.h>

/***********************************************************************************
* Subrountine:	ALGDes_PR_Run
* Function:
* Input:
* Output:
* Description:
* Date:
* ModifyRecord:
**********************************************************************************/
UINT8 ALGDes_PR_Run(UINT8 nType,UINT8 nMode,UINT8* pIn,UINT8* pOut,UINT16 nDataLen,UINT8* pKey,UINT8* pIV)
{
	UINT8 nKenLen = 0;
	UINT8 nRet, type;
	mbedtls_des3_context des3_ctx;
	mbedtls_des_context *des_ctx;
	des_ctx = (mbedtls_des_context *)&des3_ctx;
	switch (nMode)
	{
		case DES_ECB:
		case DES_CBC: 
			nKenLen = 8;
			if(nType == DES_DECRYPT)
			{
				mbedtls_des_setkey_dec(des_ctx, pKey);
				type = MBEDTLS_DES_DECRYPT;
			}
			else
			{
				mbedtls_des_setkey_enc(des_ctx, pKey);
				type = MBEDTLS_DES_ENCRYPT;
			}
			if(nMode ==DES_CBC )
			{
				nRet = mbedtls_des_crypt_cbc(des_ctx, type, nDataLen, pIV, pIn, pOut);	
			}
			else
			{
				while(nDataLen)
				{
					nRet = mbedtls_des_crypt_ecb(des_ctx, pIn, pOut);	
					if(nRet != 0)
					{
						return RT_FAIL;
					}
					nDataLen -= 8;
					pIn += 8;
					pOut += 8;
				}
			}
		
			break;
		case DES3_ECB:
		case DES3_CBC: 

			nKenLen = 24;
			if(nType == DES_DECRYPT)
			{
				mbedtls_des3_set3key_dec(&des3_ctx, pKey);
				type = MBEDTLS_DES_DECRYPT;
			}
			else
			{
				mbedtls_des3_set3key_enc(&des3_ctx, pKey);
				type = MBEDTLS_DES_ENCRYPT;
			}
			if(nMode ==DES3_CBC )
			{
				nRet = mbedtls_des3_crypt_cbc(&des3_ctx, type, nDataLen, pIV, pIn, pOut);	
			}
			else
			{
				while(nDataLen)
				{
					nRet = mbedtls_des3_crypt_ecb(&des3_ctx, pIn, pOut);	
					if(nRet != 0)
					{
						return RT_FAIL;
					}
					nDataLen -= 8;
					pIn += 8;
					pOut += 8;
				}
			}
			break;
		default :return 1;
	}

	if(nRet != 0)
	{
		nRet = 1;
	}

	return nRet;
}
